<template>
  <a-modal
    :visible="visibleOfPro"
    title="上传图片"
    cancelText="取消"
    okText="提交"
    @ok="submit"
    @cancel="cancel"
  >
    <a-form
      :rules="formRules"
      ref="formRef"
      :model="formData"
      :label-col="labelCol"
      :wrapperCol="wrapperCol"
    >
      <div v-for="item in formColumns" :key="item.props">
        <a-form-item v-if="item.show" :label="item.label" :name="item.props">
          <!-- 日期 -->
          <a-date-picker
            @change="onDateChange"
            style="width: 100%"
            v-if="item.ele === 'datePicker'"
            v-model:value="formData[item.props]"
          ></a-date-picker>
          <!-- 文本域 -->
          <a-textarea
            v-if="item.ele === 'textarea'"
            v-model:value="formData[item.props]"
          ></a-textarea>
          <!-- 上传 -->
          <div @click.stop="handleClick">
            <a-upload
              v-if="item.ele === 'upload'"
              :before-upload="beforeUpload"
              :fileList="fileList"
              :remove="handleRemove"
            >
              <a-button>
                <upload-outlined></upload-outlined>
                上传
              </a-button>
            </a-upload>
          </div>
        </a-form-item>
      </div>
    </a-form>
  </a-modal>
</template>

<script setup>
import { cloneDeep } from "lodash";
import global from "../../../global/global.vue";
import { defineProps, ref, defineEmits, watch } from "vue";
import {
  sgzytzMultifileUpload,
  getsgzytzSaveOrUpdateAPI,
} from "@/api/module/constructAndImplement";
import { message } from "ant-design-vue";

const props = defineProps({
  visibleOfPro: Boolean,
  totalData: Object,
});

const emits = defineEmits(["close"]);

// 项目id
const projectId = global.xmid;

// 表单实例
const formRef = ref();

// 表单设置
const labelCol = { span: 6 };
const wrapperCol = { span: 18 };

// 表单渲染规则
const formColumns = ref([
  { ele: "datePicker", props: "sgzjdtTime", label: "时间", show: true },
  { ele: "textarea", props: "sgzjdtMs", label: "描述", show: true },
  { ele: "datePicker", props: "zpmtTime", label: "时间", show: false },
  { ele: "textarea", props: "zpmtMs", label: "描述", show: false },
  { ele: "datePicker", props: "zygcdmtTime", label: "时间", show: false },
  { ele: "textarea", props: "zygcdmtMs", label: "描述", show: false },
  { ele: "upload", props: "zp", label: "图片", show: true },
]);

// zp的自定义校验
const zpValidator = (rule, value) => {
  if (fileList.value.length === 0) {
    return Promise.reject("请上传");
  } else {
    return Promise.resolve();
  }
};
// 表单校验规则
const formRules = {
  des: [{ required: true, message: "请输入", trigger: "blur" }],
  time: [{ required: true, message: "请选择", trigger: "change" }],
  zp: [{ validator: zpValidator, trigger: "change" }],
};

// 表单数据
const formData = ref({
  time: "",
  des: "",
  zp: "",
});

// 监听totalData
watch(
  () => props.totalData,
  (newV, oldV) => {
    formData.value = cloneDeep(newV);
    if (newV.whitchPartVal === "1") {
      formColumns.value[0].show = true;
      formColumns.value[1].show = true;
      formColumns.value[2].show = false;
      formColumns.value[3].show = false;
      formColumns.value[4].show = false;
      formColumns.value[5].show = false;
      if (newV.sgzjdt) {
        fileList.value = newV.sgzjdt.split(",").map((item) => ({
          name: "图片",
          id: item,
        }));
        fileId.value = newV.sgzjdt.split(",");
      }
    }
    if (newV.whitchPartVal === "2") {
      formColumns.value[0].show = false;
      formColumns.value[1].show = false;
      formColumns.value[2].show = true;
      formColumns.value[3].show = true;
      formColumns.value[4].show = false;
      formColumns.value[5].show = false;
      if (newV.zpmt) {
        fileList.value = newV.zpmt.split(",").map((item) => ({
          name: "图片",
          id: item,
        }));
        fileId.value = newV.zpmt.split(",");
      }
    }
    if (newV.whitchPartVal === "3") {
      formColumns.value[0].show = false;
      formColumns.value[1].show = false;
      formColumns.value[2].show = false;
      formColumns.value[3].show = false;
      formColumns.value[4].show = true;
      formColumns.value[5].show = true;
      if (newV.zygcdmt) {
        fileList.value = newV.zygcdmt.split(",").map((item, index) => ({
          name: "图片" + (index + 1),
          id: item,
        }));
        fileId.value = newV.zygcdmt.split(",");
      }
    }
  },
  {
    deep: true,
  }
);

// 选择时间
const onDateChange = (date, dateString) => {
  formData.value.sgzjdtTime = dateString;
  formData.value.zpmtTime = dateString;
  formData.value.zygcdmtTime = dateString;
};

// 文件去除
const handleRemove = (file) => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
  fileId.value = fileId.value.filter((item) => item !== file.id);
  console.log(fileId.value);
};

// 点击上传
const fileList = ref("");
// 判断文件类型
const imageType = ["image/jpeg", "image/png", "image/gif", "image/bmp"];
const beforeUpload = (file) => {
  const isType = imageType.includes(file.type);
  if (!isType) {
    return message.error("上传文件格式错误!");
  }
  if (props.totalData.whitchPartVal === "3") {
    fileList.value = [...fileList.value, file];
  } else {
    fileId.value = [];
    fileList.value = [file];
  }

  return false;
};

// 点击提交
let fileId = ref([]);
// 公共逻辑上传
const publicSubmit = async (type) => {
  const formDataData = new FormData();
  fileList.value.forEach((item) => {
    formDataData.append("files", item);
  });
  formDataData.append("type", type);
  const res = await sgzytzMultifileUpload(formDataData);
  fileId.value = res.data[type];
};
const submit = async () => {
  await formRef.value.validate();
  // 总进度上传
  if (props.totalData.whitchPartVal === "1") {
    if (fileId.value.length === 0) {
      await publicSubmit("1");
    }
    const paramsData = {
      id: props.totalData.id,
      xmid: projectId,
      sgzjdt: fileId.value.join(","),
      sgzjdtMs: formData.value.sgzjdtMs,
      sgzjdtTime: formData.value.sgzjdtTime,
    };
    console.log(paramsData);
    await getsgzytzSaveOrUpdateAPI(paramsData);
    //  平面上传
  } else if (props.totalData.whitchPartVal === "2") {
    if (fileId.value.length === 0) {
      await publicSubmit("2");
    }
    const paramsData = {
      id: props.totalData.id,
      xmid: projectId,
      zpmt: fileId.value.join(","),
      zpmtMs: formData.value.zpmtMs,
      zpmtTime: formData.value.zpmtTime,
    };
    await getsgzytzSaveOrUpdateAPI(paramsData);
    // 多个上传
  } else if (props.totalData.whitchPartVal === "3") {
    if (fileList.value.length !== fileId.value.length) {
      const formDataData = new FormData();
      fileList.value.splice(0, fileId.value.length);
      fileList.value.forEach((item) => {
        formDataData.append("files", item);
      });
      formDataData.append("type", "3");
      // 上传
      const res = await sgzytzMultifileUpload(formDataData);
      fileId.value = fileId.value.concat(res.data[3]);
    }
    // 提交
    const paramsData = {
      id: props.totalData.id,
      xmid: projectId,
      zygcdmt: fileId.value.join(","),
      zygcdmtMs: formData.value.zygcdmtMs,
      zygcdmtTime: formData.value.zygcdmtTime,
    };
    await getsgzytzSaveOrUpdateAPI(paramsData);
  }
  // 关闭弹窗清除数据
  message.success("提交成功");
  fileList.value = "";
  formRef.value.resetFields();
  emits("close", false);
};

// 取消
const cancel = () => {
  fileList.value = "";
  formRef.value.resetFields();
  emits("close", false);
};
</script>

<style lang="scss" scoped></style>
